<?php 
/*
Plugin Name: Unglued Promotion
Plugin URI: http://unglud.ru/category/promotion/
Description: Плагин активирует всплывающую панель внизу страницы, на которой вы можете разместить материал рекламного характера, какое-либо сообщение или новость.
Version: 1.0
Author: Alexander 'unglued' Matrosov
Author URI: http://unglud.ru/
*/

/*  Copyright 2010  Alexander 'unglued' Matrosov  (email: unglud@gmail.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

$ung_prom_version = '1.0';
$table_name = $wpdb->prefix . "ung_prom";

register_activation_hook(__FILE__,'promotion_install');

if(isset($_POST["row"])){
	if($_POST["row"] == "update"){
		$updateLen = count($_POST["id"]);
		print_r($_POST["active"]);
		for($i=0; $i<$updateLen; $i++){
			//$wpdb->query("UPDATE  $table_name SET `style` =  '".$_POST["style"][$i]."', `html` =  '".$_POST["html"][$i]."', `active` =  '".$_POST["active"][$i]."' WHERE `id` =".$_POST["id"][$i]." LIMIT 1 ;");
			$wpdb->query("UPDATE  $table_name SET `style` =  '".$_POST["style"][$i]."', `html` =  '".$_POST["html"][$i]."' WHERE `id` =".$_POST["id"][$i]." LIMIT 1 ;");
		}
	}
	if($_POST["row"] == "add"){
		$wpdb->query( $wpdb->prepare( "INSERT INTO $table_name (name, style, html) VALUES(%s, %s, %s)",
		$_POST["name"], $_POST["style"], $_POST["html"]));		
	}
}


function promotion_install(){
	global $wpdb, $ung_prom_version, $table_name;

	if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
		add_option("ung_prom_version", $ung_prom_version);
		add_option('ung_prom_showMeerkatOnLoad', 'false');
		add_option('ung_prom_delay', '');
		add_option('ung_prom_closeButton', 'none');
		add_option('ung_prom_dontShow', 'none');
		add_option('ung_prom_dontShowExpire', '');
		add_option('ung_prom_meerkatPosition', 'bottom');
		add_option('ung_prom_animation', 'slide');
		add_option('ung_prom_animationSpeed', 'slow');
		add_option('ung_prom_animationSpeedNum', '');
		
		$sql = "CREATE TABLE " . $table_name . " (
				id mediumint(9) NOT NULL AUTO_INCREMENT,
				name VARCHAR(255) NOT NULL,
				style text NOT NULL,
				html text NOT NULL,
				active tinyint(1) DEFAULT '1' NOT NULL,
				UNIQUE KEY id (id)
			);";
		
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
		
		$welcome_name = "My first promotion";
  	$welcome_style = "
				#meerkat {
					width: 100%;
					display: none;
					height:89px;
					background:url(images/meerkat_bg.png) repeat-x;
				}
				
				#meerkat .content{
					padding-top:40px;
					width:960px;
					margin:0 auto;
				}
				#meerkat .meer_text{
					padding-left:135px;
				}
				
				#meerkat h1{color:#FFF; padding-bottom:5px;}
				#meerkat p{color:#F4F4F4;}
				
				#meerkat .meer_img{
					position:absolute;
					bottom:0px;
					width:125px;
					height:89px;
					background:url(images/meerkat_img.png) no-repeat;
				}
				
				#meerkat a{
					color: #FFF;
					font-weight: bold;
				}
				#meerkat a:hover{
					color: #FFF;
					font-weight: bold;
					text-decoration:underline;
				}
				
				#meerkat a.dont-show{
					color: #FFF;
					font-size:10px;
					position:absolute;
					bottom:0px;
					right:5px;
					cursor:pointer;
				}
				
				#meerkat .close-meerkat {
					position: absolute;
					top: 40px;
					right: 3px;
					width:16px;
					height:16px;
					background:url(images/close.png) 0 -16px no-repeat;
				}
				
				#meerkat .close-meerkat:hover {
					background:url(images/close.png) no-repeat;
				}";
		$welcome_html = '
			<div class="meer_img"></div>
			<div class="meer_text">
			<h1>КАЛЕНДАРИК ПИНАРИК</h1> 
			<p>Лучшее изобретение для самомотивации и рационального расходования времени. <a href="http://unglud.ru/pages/pinarik/#slon">Скачать прямо сейчас!</a><a class="dont-show">больше не показывать</a></p>
			<div class="close-meerkat"></div>
			</div>';
  	$insert = "INSERT INTO " . $table_name .
            " (name, style, html) " .
            "VALUES ('" . $wpdb->escape($welcome_name) . "','" . $wpdb->escape($welcome_style) . "','" . $wpdb->escape($welcome_html) . "')";

		$results = $wpdb->query( $insert );
	}
}

$showMeerkatOnLoad = get_option('ung_prom_showMeerkatOnLoad');
$ung_prom_delay = get_option('ung_prom_delay');
$closeButton = get_option('ung_prom_closeButton');
$dontShow = get_option('ung_prom_dontShow');
$dontShowExpire = get_option('ung_prom_dontShowExpire');
$meerkatPosition = get_option('ung_prom_meerkatPosition');
$animation = get_option('ung_prom_animation');
$animationSpeed = get_option('ung_prom_animationSpeed');
$animationSpeedNum = get_option('ung_prom_animationSpeedNum');

$curPanel = 0;

function getRandPanel(){
	global $wpdb,$curPanel, $table_name;
	if(!$curPanel){
		$ids=$wpdb->get_col("SELECT id FROM $table_name WHERE active=1");
		srand(time());
		$curPanel=$wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id=%s", $ids[array_rand($ids)]), ARRAY_A);
	}
	return $curPanel;
}

function past_meerkat(){
	$path = plugins_url('/unglued-promotion/');
	//wp_enqueue_script('jquery-meerkat', $path.'jquery.meerkat.1.0.js');
	$script = '<script type="text/javascript" src="'.$path.'jquery.meerkat.1.0.js"></script>';
	$script .= '<link rel="stylesheet" href="'.$path.'meerkat_style.css" type="text/css" media="screen" />';
	$curPanel = getRandPanel();
	$script .='<style type="text/css">'.$curPanel["style"].'</style>';
  return $script;
}

function past_meerkat_div(){
	global $showMeerkatOnLoad, $ung_prom_delay, $closeButton, $dontShow, $dontShowExpire, $meerkatPosition, $animation, $animationSpeed, $animationSpeedNum;
	$script .= '<script type="text/javascript">$(document).ready(setTimeout(function(){meerkat({';
	$script .= "showMeerkatOnLoad: '".(($showMeerkatOnLoad !='')? $showMeerkatOnLoad : 'false')."',
										close: '".(($closeButton !='')? $closeButton : 'none')."',
										dontShow: '".(($dontShow !='')? $dontShow : 'none')."',
										dontShowExpire: ".(($dontShowExpire !='')? $dontShowExpire : '0').",
										meerkatPosition: '".(($meerkatPosition !='')? $meerkatPosition : 'bottom')."',
										animation: '".(($animation !='')? $animation : 'slide')."',";
	if($animationSpeed != "num") $script .= "animationSpeed: '".(($animationSpeed !='')? $animationSpeed : 'slow')."'";
	else $script .= "animationSpeed: ".(($animationSpeedNum !='')? $animationSpeedNum : '100');
	$script  .= '});}, '.(($ung_prom_delay !='')? $ung_prom_delay : '0').'));</script>';
	$curPanel = getRandPanel();
	$script .= '<div id="meerkat"><div class="content">'.$curPanel["html"].'</div></div>';
	return $script;
}

add_action('admin_menu', 'add_promotion_menu');
function add_promotion_menu(){
	add_options_page('Unglued Promotion', 'Unglued Promotion', 8, 'unglued_promotion', 'promotion_settings');
}

function promotion_settings(){
	global $wpdb, $showMeerkatOnLoad, $ung_prom_delay, $closeButton, $dontShow, $dontShowExpire, $meerkatPosition, $animation, $animationSpeed, $animationSpeedNum, $table_name;
?>
<div class="wrap">
<h2>Настройки Unglued Promotion</h2>

<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>


<table class="widefat" style="margin-top: 1em;"> 
	<thead><tr><th scope="col" colspan="2">Настройки отображения</th></tr></thead> 
 
	<tbody> 


<tr valign="top">
<th scope="row">Отображать панель сразу при загрузке</th>
<td><input name="ung_prom_showMeerkatOnLoad" type="checkbox" value="true" <?php if($showMeerkatOnLoad == 'true') echo"checked"; ?> /></td>
</tr>

<tr valign="top">
<th scope="row">Задержка перед появлением</th>
<td><input type="text" name="ung_prom_delay" value="<?php echo $ung_prom_delay; ?>" /> миллисекунд</td>
</tr>

<tr valign="top">
<th scope="row">Позволять временно закрывать панель</th>
<td><input name="ung_prom_closeButton" type="checkbox" value=".close-meerkat" <?php if($closeButton == '.close-meerkat') echo"checked"; ?> /></td>
</tr>

<tr valign="top">
<th scope="row">Позволять совсем закрывать панель</th>
<td><input name="ung_prom_dontShow" type="checkbox" value=".dont-show" <?php if($dontShow == '.dont-show') echo"checked"; ?> /></td>
</tr>
 
<tr valign="top">
<th scope="row">Не показвать (дней)</th>
<td><input type="text" name="ung_prom_dontShowExpire" value="<?php echo $dontShowExpire; ?>" /> (0 - до закрытия браузера, 0.5 - 12 часов, 1- один день и т.д.)	</td>
</tr>

<tr valign="top">
<th scope="row">Позиция</th>
<td><label>
      <input type="radio" name="ung_prom_meerkatPosition" value="bottom" id="RadioGroup1_0" <?php if($meerkatPosition == 'bottom') echo"checked"; ?>>
      Внизу</label>&nbsp;&nbsp;
      <label>
      <input type="radio" name="ung_prom_meerkatPosition" value="top" id="RadioGroup1_1" <?php if($meerkatPosition == 'top') echo"checked"; ?>>
      Вверху</label></td>
</tr>

<tr valign="top">
<th scope="row">Анимация</th>
<td><label>
      <input type="radio" name="ung_prom_animation" value="slide" id="RadioGroup2_0" <?php if($animation == 'slide') echo"checked"; ?>>
      Слайдер</label>&nbsp;&nbsp;
      <label>
      <input type="radio" name="ung_prom_animation" value="fade" id="RadioGroup2_1" <?php if($animation == 'fade') echo"checked"; ?>>
      Фэйдер</label></td>
</tr>

<tr valign="top">
<th scope="row">Скорость анимации</th>
<td>
	<select name="ung_prom_animationSpeed" size="1">
	  <option value="num" <?php if($animationSpeed == 'num') echo"selected"; ?> >Милисек.</option>
	  <option value="fast" <?php if($animationSpeed == 'fast') echo"selected"; ?> >Быстро</option>
	  <option value="slow" <?php if($animationSpeed == 'slow') echo"selected"; ?> >Медленно</option>
  </select>
	<input type="text" name="ung_prom_animationSpeedNum" value="<?php echo $animationSpeedNum; ?>" /></td>
</tr>
</tbody>
</table>

<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="ung_prom_showMeerkatOnLoad,ung_prom_delay,ung_prom_closeButton,ung_prom_dontShow,ung_prom_dontShowExpire,ung_prom_meerkatPosition,ung_prom_animation,ung_prom_animationSpeed,ung_prom_animationSpeedNum" />

<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
</p>

</form>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']."?page=unglued_promotion#panels"; ?>">
<a name="panels" id="panels"></a>
<h3>Список панелей</h3>
<?php
	$get_panels = "SELECT * FROM $table_name ORDER BY  `id` ASC";
	$panels_list = $wpdb->get_results($get_panels, ARRAY_A);
	
	for($i=0; $i<$wpdb->num_rows; $i++){ ?>
	<input type="hidden" name="id[]" value="<?php echo $panels_list[$i]["id"]; ?>" />
  <table class="widefat" style="margin-top: 1em;"> 
    <thead><tr><th scope="col"><?php echo $panels_list[$i]["name"]; ?><!--&nbsp;активно&nbsp;
    	<input type="radio" name="active[]" value="1" id="RadioGroup3_1<?php echo $panels_list[$i]["id"]; ?>" <?php if($panels_list[$i]["active"] == '1') echo"checked"; ?>>да&nbsp;
      <input type="radio" name="active[]" value="0" id="RadioGroup3_2<?php echo $panels_list[$i]["id"]; ?>" <?php if($panels_list[$i]["active"] == '0') echo"checked"; ?>>нет -->
     </th></tr></thead> 
    <tbody>
      <tr><td>
      		<textarea name="style[]" cols="100" rows="10"><?php echo $panels_list[$i]["style"]; ?></textarea>
      </td></tr>
      <tr><td>
      		<textarea name="html[]" cols="100" rows="10"><?php echo $panels_list[$i]["html"]; ?></textarea>
      </td></tr>
      <?php /*?><tr><td>
      		<iframe width="100%" src="<?php echo $path; ?>view.php?id=<?php echo $panels_list[$i]["id"]; ?>"></iframe>
      </td></tr><?php */?>
    </tbody>
  </table>
	
	<?php } ?>
<input type="hidden" name="row" value="update" />

<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
</p>

</form>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']."?page=unglued_promotion#panels"; ?>">
<h3>Добавить новую панель</h3>
  <table class="widefat" style="margin-top: 1em;"> 
    <thead><tr><th scope="col"><input type="text" name="name" value="название" /></th></tr></thead> 
    <tbody>
      <tr><td>
      		<textarea name="style" cols="100" rows="10">
#meerkat {
	width: 100%;
	display: none;
}
</textarea>
      </td></tr>
      <tr><td>
      		<textarea name="html" cols="100" rows="10"><h1>MY NEW PROMOTION</h1> </textarea>
      </td></tr>
    </tbody>
  </table>
<input type="hidden" name="row" value="add" />

<p class="submit">
<input type="submit" class="button-primary" value="Добавить" />
</p>

</form>

</div>

<?php } ?>